package cn.kongwg.es.utils;

import cn.kongwg.es.entity.JBook;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @author kongwg
 * @create 2021-04-02 18:42
 */
@Component
public class HttpParseUtils {
    public  List<JBook> parseJD(String keyword,String page) throws IOException {
        String url = "https://search.jd.com/Search?keyword="+keyword+"&page="+page;
        Document document = Jsoup.parse(new URL(url), 30000);

        Element elementById = document.getElementById("J_goodsList");

        Elements liTag = elementById.getElementsByTag("li");
//        System.out.println(liTag.html());
        List<JBook> books = new ArrayList<>();
        for (Element el : liTag) {
            String imgUlr = el.getElementsByTag("img").eq(0).attr("data-lazy-img");
            String price = el.getElementsByClass("p-price").eq(0).text();
            String title = el.getElementsByClass("p-name").eq(0).text();
            System.out.println(imgUlr);
            System.out.println(price);
            System.out.println(title);
            books.add(new JBook(title, price, imgUlr));
        }
        return books;
    }
}
